package com.heima.search.service.impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private IApUserSearchService userSearchService;
    /**
     * 搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if (StringUtils.isEmpty(dto.getSearchWords()) || StringUtils.isEmpty(dto.getSearchWords().trim())){
            PageResponseResult result = new PageResponseResult(dto.getPage() - 1, dto.getSize()
                    , 0L, new ArrayList<ApArticleSearch>());
            return ResponseResult.okResult(result);
        }
        //查询条件
        //根据关键字查询
        QueryBuilder query = QueryBuilders.matchQuery("title",dto.getSearchWords());
        //分页查询 参数 1 当前页 2每页条数 3排序方向 4排序字段
        Pageable page = PageRequest.of(dto.getPage().intValue() -1,dto.getSize(), Sort.Direction.DESC,"publishTime");
        Page<ApArticleSearch> search = articleRepository.search(query, page);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                search.getTotalElements(), search.getContent());

        //异步记录用户的查询记录
        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setKeyword(dto.getSearchWords());
        userSearch.setCreatedTime(new Date());
        //判断用户是否登录 如果登录 设置userId 否则设置设备id
        User user = AppThreadLocalUtil.get();
        if (user == null){
            userSearch.setEquipmentId(dto.getEquipmentId());
        }else {
            userSearch.setUserId(user.getUserId());
        }
        userSearchService.saveRecord(userSearch);
        return result;
    }
}
